/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.stream.commontools.concurrent.resourcepool.limited;

import cn.ac.iie.stream.commontools.concurrent.resourcepool.ResourcePool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author zwlin
 * @param <ResourceType> 资源池里的数据类型
 */
public abstract class SimpleLimitedResourcePool<ResourceType> implements ResourcePool<ResourceType> {

	private final BlockingQueue<ResourceType> resourceQueue;

	/**
	 *
	 * @param capacity 缓存的资源量
	 */
	public SimpleLimitedResourcePool(int capacity) {
		this.resourceQueue = new LinkedBlockingQueue<ResourceType>(capacity);
		for (int i = 0; i < capacity; ++i) {
			resourceQueue.add(GetNewResource());
		}
	}

	/**
	 * 获取资源
	 *
	 * @return 如果队列空，阻塞等待。如果出错，返回空
	 */
	@Override
	public ResourceType BorrowResource() {
		try {
			return resourceQueue.take();
		} catch (InterruptedException ex) {
			return null;
		}
	}

	/**
	 * 归还资源
	 *
	 * @param resource 归还的资源
	 * @return 队列未满，归还成功，返回true；如果队列满，归还失败，返回false
	 */
	@Override
	public boolean ReturnResource(ResourceType resource) {
		try {
			return resourceQueue.offer(resource);
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	abstract public ResourceType GetNewResource();

}
